package spectrum;

import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.fpga.tSPI;


public class HW_SPI extends SensorBase {

    public class HW_SPI_Result
    {
        char[] output = {'.','.','.'};
    }


    tSPI spi;
    DigitalModule module;
    int slot;
    int clockPin;
    int dataOutPin;
    int dataInPin;
    int chipSelectPin;


    public HW_SPI( int slotParam, int clockPinParam, int dataOutPinParam, int dataInPinParam, int chipSelectPinParam )
    {
        slot = slotParam;
        clockPin = clockPinParam;
        dataOutPin = dataOutPinParam;
        dataInPin = dataInPinParam;
        chipSelectPin = chipSelectPinParam;

        // get our module
        module = DigitalModule.getInstance(slot);


        // allocate pins
        module.allocateDIO(clockPin, false);
        module.allocateDIO(dataOutPin, false);
        module.allocateDIO(dataInPin, true);
        module.allocateDIO(chipSelectPin, false);

        // setup for SPI
        tSPI.writeChannels_SCLK_Channel(DigitalModule.remapDigitalChannel(clockPin-1));

        tSPI.writeChannels_MOSI_Channel(DigitalModule.remapDigitalChannel(dataOutPin-1));

        tSPI.writeChannels_MISO_Channel(DigitalModule.remapDigitalChannel(dataInPin-1));
    }

    public void initialize()
    {
        // set chip select low to start
        module.setDIO(chipSelectPin, true);

        // data is valid on rising edge of clock
        tSPI.writeConfig_DataOnFalling(false);

        // set the bit order
        tSPI.writeConfig_MSBfirst(true);

        tSPI.strobeReset();
        tSPI.strobeClearReceivedData();
    }

    public HW_SPI_Result getData( )
    {
        HW_SPI_Result result = new HW_SPI_Result();
        
        // select the chip
        module.setDIO(chipSelectPin, false);

        // write the 5 bit command
        // set the width
        tSPI.writeConfig_BusBitWidth(8);

        // write the data to load
        tSPI.writeDataToLoad('g');

        // strobe out the data
        tSPI.strobeLoad();

        // wait for completion
        while( !tSPI.readStatus_Idle() )
        {
            java.lang.Thread.yield();
        }
        
        for(int i=0; i<=0;i++)
        {
            // clear the data to load
            tSPI.writeDataToLoad(0x0);

            // clear received data
            tSPI.strobeClearReceivedData();

            // strobe in the data
            tSPI.strobeLoad();


            // wait for completion
            while( tSPI.readReceivedElements() == 0 )
            {
                java.lang.Thread.yield();
            }

            // strobe in the received data
            tSPI.strobeReadReceivedData();

            // read the data
           result.output[i] = (char)tSPI.readReceivedData();
        }

        // deselect the chip
        module.setDIO(chipSelectPin, true);

        
        return result;
    }
}